package com.example.service;

import com.example.dao.StudentDao;
import com.example.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wj on 17-6-30.
 */
@Service
public class StudentService {

    @Autowired
    private StudentDao dao;

    public List<Student> findByCondition(Student student) {

        List<Student> result = null;

        //生成查询条件
        Specification<Student> specification = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (student.getId() != null) {
                predicates.add(cb.equal(root.get("id"), student.getId()));
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        result = dao.findAll(specification);

        return result;
    }
}
